const app = getApp();
const towxImg = require('../../../utils/towxImg');
import cloud from '../../../utils/cloud';
const cloud1 = require("../../../utils/api");

// pages/blogs/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hide: app.globalData.hide,
    article: '',
    scrollTop: 0
  },

  getOneDetail(id, type) {
    const that = this;
    let { article } = that.data;
    cloud1.cloudGet("blogs", { _id: id }).then((res) => {
      article = towxImg.dealWithRichText(res[0].md, type);
      this.setData({
        article
      })
    });
  },

  async getMarkdown(title, id, type) {
    const that = this;
    wx.showLoading({
      title: 'Loading...',
    })
    const c1 = cloud();
    await c1.init();
    c1.downloadFile({
      fileID: 'cloud://love-0g1b6yqybf5521f5.6c6f-love-0g1b6yqybf5521f5-1316718936/md/' + title + '.md'
    }).then(res => {
      let fs = wx.getFileSystemManager();
      let result = fs.readFileSync(res.tempFilePath, "utf-8");
      const article = towxImg.dealWithRichText(result);
      // const article = app.towxml(result, "markdown", {
      //   base: '',
      //   theme: 'light'
      // });
      that.setData({
        article
      }, () => {
        wx.hideLoading();
      })
    }).catch(err => {
      // console.log(err);
      that.getOneDetail(id, type);
    })
  },

  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let { title, id, type } = options;
    const hide = app.globalData.hide;
    this.setData({ hide });
    if (hide) return;
    wx.setNavigationBarTitle({
      title: title,
    });
    this.getMarkdown(title, id, type);
    // this.getOneDetail(id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})